//
//  MJOAuthViewController.swift
//  新浪微博
//
//  Created by MaJi on 16/4/9.
//  Copyright © 2016年 MaJi. All rights reserved.
//
//1. 使用webView加载登录授权的页面
import UIKit
import SVProgressHUD
//全局变量
//private let userInfoKey = "com.baidu.userifonKey"
class MJOAuthViewController: UIViewController {

    let webview = UIWebView()
    override func loadView() {
        view = webview
        webview.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        设置导航条
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, action: "fullAcount")
//        2.使用web加载授权页面
//        https://api.weibo.com/oauth2/authorize这是微博OAuth2的authorize接口  注意拼接的时候别忘啦加? &号
        let urlString:String = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "4117975720" + "&redirect_uri=" + "http://www.baidu.com"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webview.loadRequest(request)
    }
//    关闭按钮
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
//    自动填充按钮
    func fullAcount(){
        webview.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '15036691713', document.getElementById('passwd').value = 'MJ123456' ")
    }
//    
}
//遵守协议 类扩展,分模块
extension MJOAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
//        开始加载网页.添加等待指示器
        SVProgressHUD.show()
            }
    
    func webViewDidFinishLoad(webView: UIWebView) {
//        加载完毕.移除指示器
        SVProgressHUD.dismiss()
        let webviewTitle = webview.stringByEvaluatingJavaScriptFromString("document.title")
        title = webviewTitle

    }
    override func viewWillDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    
    //协议方法返回值为 bool类型 如果返回 true 就可才正常工作,否则就不能够工作
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString ?? ""
        //满足字符串中包好了 code= 只要有code= 这个字符串就表示授权成功
//        print("-----")
//        print(urlString)
        let flag = "code="
        if urlString.containsString(flag) {
            let range = urlString.rangeOfString(flag)!
            let code = urlString.substringFromIndex((range.endIndex))
//            print("----")
//            print(code)
//            使用授权码,获取access_token
            MJUserAccountViewModel.sharedAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                if !isSuccess {
                    SVProgressHUD.showErrorWithStatus("登录失败")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("登录成功")
                //    跳转到欢迎页面
//                   注意1:不能这样跳转,Oauth界面是modal进来的要手动dismiss释放页面
//                let vc = MJWelcomeViewController()
//                self.navigationController?.pushViewController(vc, animated: true)         跳转之前释放
                self.navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in
//                    登录成功,跳转到欢迎页面的跟控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(MJSwitchRootViewController, object: nil)
                })
                
            })
//
//            //不加载授权成功的回调页面
            return false
//             loadAccessToken(code)
        }
        return true
    }

}






